<template>
  <!-- 面包屑 -->
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item><b>首页</b></el-breadcrumb-item>
    </el-breadcrumb>
  </div>

  <!-- 卡片容器 -->
  <div style="display: flex; justify-content: space-between; margin: 40px 20px 20px 20px">
    <!-- 第一个卡片 -->
    <el-card class="card-style">
      <div>
        <el-table :data="tabletask" stripe border style="width: 100%">
          <el-table-column prop="task" label="任务" align="center" @click="handleTaskClick(scope.row)"/>
          <el-table-column label="操作" align="center" width="240">
            <template #default="scope">
              <el-button type="primary" @click="handleNavigate(scope.row)">进入</el-button>
              <el-button type="danger" @click="taskDeleteHandler(scope.$index, scope.row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <br>
        <el-button @click="taskAddState = true" style="width: 480px">新增</el-button>
      </div>
    </el-card>

    <!-- 第二个卡片 -->
    <el-card class="card-style">
      <div>
        <el-table :data="tabletodo" stripe border style="width: 100%">
          <el-table-column prop="todo" label="待办" align="center"/>
          <!-- 删除操作列 -->
          <el-table-column label="操作" align="center" width="240">
            <template #default="scope">
              <el-button
                  type="danger"
                  @click="todoDleteHandler(scope.$index, scope.row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <br>
        <el-button @click="todoAddState = true" style="width: 480px">新增</el-button>
      </div>
    </el-card>
  </div>

  <!-- 任务新增模态框 -->
  <el-dialog v-model="taskAddState" title="新增任务" width="400px" @open="taskAddOnOpen" center>
    <el-form ref="taskAddRef" :model="taskAdd" :rules="rules" label-width="120px">
      <el-form-item prop="task" label="添加任务">
        <el-select v-model="taskAdd.task" placeholder="请选择任务">
          <el-option label="通告分组管理" value="通告分组管理"></el-option>
          <el-option label="通告管理" value="通告管理"></el-option>
          <el-option label="通告汇总" value="通告汇总"></el-option>
          <el-option label="会议预约" value="会议预约"></el-option>
          <el-option label="会议签到" value="会议签到"></el-option>
          <el-option label="充值信息汇总" value="充值信息汇总"></el-option>
          <el-option label="出境申请" value="出境申请"></el-option>
          <el-option label="加班申请" value="加班申请"></el-option>
          <el-option label="出警申请" value="出警申请"></el-option>
          <el-option label="请假申请" value="请假申请"></el-option>
          <el-option label="销假申请" value="销假申请"></el-option>
          <el-option label="日常报销申请" value="日常报销申请"></el-option>
          <el-option label="出差报销申请" value="出差报销申请"></el-option>
          <el-option label="慰问金申请" value="慰问金申请"></el-option>
          <el-option label="证件借还" value="证件借还"></el-option>
        </el-select>
      </el-form-item>
      </el-form>
    <template #footer>
  <span class="dialog-footer">
    <el-button @click="taskAddOnReset">取消</el-button>
    <el-button type="primary" @click="taskAddOnSubmit">确认</el-button>
  </span>
    </template>
  </el-dialog>

  <!-- 待办新增模态框 -->
  <el-dialog v-model="todoAddState" title="添加待办" width="400px" @open="todoAddOnOpen" center>
    <el-form ref="todoAddRef" :model="todoAdd" :rules="todoRules" label-width="120px">
      <el-form-item prop="todo" label="添加待办">
        <el-input v-model="todoAdd.todo" placeholder="请输入待办事项" />
      </el-form-item>
    </el-form>
    <template #footer>
    <span class="dialog-footer">
      <el-button @click="todoAddState = false">取消</el-button>
      <el-button type="primary" @click="todoAddOnSubmit">确认</el-button>
    </span>
    </template>
  </el-dialog>

  <!-- 卡片容器 -->
  <div style="display: flex; justify-content: space-between; margin: 40px 20px 20px 20px">
    <!-- 第三个卡片 -->
    <el-card class="card-style">
      <div ref="accidentChart" style="width: 100%; height: 100%;"></div>
    </el-card>

    <!-- 第四个卡片 -->
    <el-card class="card-style">
      <div ref="vehicleChart" style="width: 100%; height: 100%;"></div>
    </el-card>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import * as echarts from 'echarts';
import { useRouter } from 'vue-router';
import request from '@/utils/homepage';

const taskAddState = ref(false);
const todoAddState = ref(false);

////////////// 路由跳转  /////////////////////////
const router = useRouter();
let clickedTaskRow = null;

const handleTaskClick = (taskRow) => {
  clickedTaskRow = taskRow;
};

const handleNavigate = (taskRow) => {
  if (taskRow) {
    let routePath = getRoutePath(taskRow.task);
    if (routePath) {
      router.push(routePath);
    } else {
      console.log('No route found for task:', taskRow.task);
    }
  } else {
    console.log('No task row provided for navigation.');
  }
};

const getRoutePath = (taskName) => {
  switch (taskName) {
    case '请假申请':
      return '/people/leave';
    case '销假申请':
      return '/people/cancelltion';
    case '出境申请':
      return '/people/exit';
    case '通告分组管理':
      return '/index/notice/group';
    case '通告管理':
      return '/index/notice';
    case '通告汇总':
      return '/index/notice/total';
    case '会议预约':
      return '/index/chamber/reserve';
    case '会议签到':
      return '/index/chamber/sign';
    case '充值信息汇总':
      return '/index/dish/pay';
    case '加班申请':
      return '/people/overtime';
    case '出警申请':
      return '/people/gopolice';
    case '日常报销申请':
      return '/reimbursement/daily/apply';
    case '出差报销申请':
      return '/reimbursement/sortie/apply';
    case '慰问金申请':
      return '/reimbursement/condole/apply';
    case '证件借还':
      return '/people/brcards';


  }
};

/////////////////////  ECharts  /////////////

const accidentChart = ref(null);
const vehicleChart = ref(null);

onMounted(() => {
  initAccidentChart();
  initVehicleChart();
});

const initAccidentChart = () => {
  const chartDom = accidentChart.value;
  chartDom.style.width = '90%';
  chartDom.style.height = '370%';
  const myChart = echarts.init(chartDom);
  const option = {
    title: { text: '各区域交通事故数量' },
    tooltip: {},
    xAxis: { data: ["上海路", "南京路", "营口道", "赤峰道", "徐州道"] },
    yAxis: {},
    series: [{ name: '交通事故数量', type: 'bar', data: [5, 20, 36, 10, 10] }]
  };
  myChart.setOption(option);
};

const initVehicleChart = () => {
  const chartDom = vehicleChart.value;
  chartDom.style.width = '90%';
  chartDom.style.height = '370%';
  const myChart = echarts.init(chartDom);
  const option = {
    title: { text: '各类型交通工具事故比例' },
    tooltip: {},
    series: [
      {
        name: '事故比例',
        type: 'pie',
        radius: '55%',
        data: [
          { value: 365, name: '汽车' },
          { value: 410, name: '摩托车' },
          { value: 134, name: '自行车' },
          { value: 105, name: '行人' }
        ]
      }
    ]
  };
  myChart.setOption(option);
};

////////////////  任务表格  ///////////////////////////

onMounted(() => {
  gettask();
});

const tabletask = ref([]);

const gettask = () => {
  request({
    url: '/task/list',
    method: 'get'
  }).then(req => {
    console.log(req);
    console.log(req.data);
    if (200 == req.data.errorCode) {
      tabletask.value = req.data.data;
    }
  });
}

///////////////  待办表格  ///////////////////////////

onMounted(() => {
  gettodo();
});

const tabletodo = ref([]);

const gettodo = () => {
  request({
    url: '/todo/list',
    method: 'get'
  }).then(req => {
    console.log(req);
    console.log(req.data);
    if (200 == req.data.errorCode) {
      tabletodo.value = req.data.data;
    }
  });
}

////////////////////////  任务新增模态框相关  //////////////////////

const rules = reactive({
  task: [
    { required: true, message: '请选择任务', trigger: 'change' }
  ]
});

const taskAddRef = ref(null);

const taskAddOnOpen = () => {
  if (taskAddRef.value) {
    taskAddRef.value.resetFields();
  }
};

const taskAddOnSubmit = () => {
  if (taskAddRef.value) {
    taskAddRef.value.validate((valid) => {
      if (valid) {
        taskAddState.value = false;
        request({
          method: 'post',
          url: '/task/add',
          data: taskAdd
        }).then(req => {
          if (req.data.errorCode === 200) {
            gettask();
            ElMessage({
              type: 'success',
              message: '添加成功'
            });
          } else {
            ElMessage.error('添加失败');
          }
        }).catch(error => {
          ElMessage.error('请求失败');
        });
      } else {
        ElMessage.error('表单校验失败');
        return false;
      }
    });
  }
};

const taskAddOnReset = () => {
  // 清空表单数据
  taskAdd.task = '';
  // 关闭对话框
  taskAddState.value = false;
};

// 新增表单初始化数据
const taskAddData = reactive({
  task: ''
});

// 新增表单绑定数据模型
const taskAdd = reactive({
  task: ''
});

///////////////////////  新增待办 /////////////////////////////
const todoAdd = reactive({
  todo: ''
});

const todoRules = reactive({
  todo: [
    { required: true, message: '待办事项不能为空', trigger: 'blur' },
    { max: 10, message: '待办事项不能超过10个字符', trigger: 'blur' }
  ]
});
const todoAddRef = ref(null);

const todoAddOnSubmit = () => {
  if (todoAddRef.value) {
    todoAddRef.value.validate((valid) => {
      if (valid) {
        todoAddState.value = false;
        request({
          method: 'post',
          url: '/todo/add',
          data: { todo: todoAdd.todo }
        }).then(req => {
          if (req.data.errorCode === 200) {
            gettodo();
            ElMessage({
              type: 'success',
              message: '添加成功'
            });
          } else {
            ElMessage.error('添加失败');
          }
        }).catch(error => {
          ElMessage.error('请求失败');
        });
      } else {
        ElMessage.error('表单校验失败');
        return false;
      }
    });
  }
};

const todoAddOnOpen = () => {
  if (todoAddRef.value) {
    todoAddRef.value.resetFields();
  }
  todoAdd.todo = '';
};

const todoAddOnReset = () => {
  todoAddState.value = false;
  todoAdd.todo = '';
};

////////////  删除  ///////////////////
const taskDeleteHandler = (rowIndex, rowData) => {
  ElMessageBox.confirm('确认删除任务 ' + rowData.task + ' 吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    request({
      method: 'delete',
      url: '/task/del/' + rowData.id
    }).then((req) => {
      if (req.data.errorCode === 200) {
        ElMessage.success('删除成功');
        gettask(); // 刷新课程列表
      } else {
        ElMessage.error('删除失败');
      }
    });
  }).catch(() => {
    ElMessage.info('已取消');
  });
};

const todoDleteHandler = (rowIndex, rowData) => {
  ElMessageBox.confirm('确认删除待办 ' + rowData.todo + ' 吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    request({
      method: 'delete',
      url: '/todo/del/' + rowData.id
    }).then((req) => {
      if (req.data.errorCode === 200) {
        ElMessage.success('删除成功');
        gettodo(); // 刷新课程列表
      } else {
        ElMessage.error('删除失败');
      }
    });
  }).catch(() => {
    ElMessage.info('已取消');
  });
};
</script>

<style scoped>
.el-breadcrumb{
  font-size: 18px;
  margin: 20px;
}
.card-style {
  height: 420px;  /* 设置卡片高度 */
  width: 620px;
}
.el-table.cell:hover {
  cursor: pointer;
  background-color: #f5f5f5;
}
</style>